package com.chen.filter;

import com.alibaba.fastjson.JSON;
import com.chen.common.BaseContext;
import com.chen.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //强转两个对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取请求路径
        String requestURI = req.getRequestURI();



        String[] urls = {"/backend/**","/front/**","/employee/login","/employee/logout","/user/login","/user/sendMsg"};
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String url : urls) {
            if (pathMatcher.match(url,requestURI)){
                chain.doFilter(req, resp);
                return;
            }
        }
        //不是以上的请求路径就判断是否登录
        Object employeeId = req.getSession().getAttribute("employee");
        //员工id不为空  说明已经登录 放行
        if (employeeId!=null){
            //放行之前将员工id存进 线程中
            BaseContext.setCurrentId((Long) employeeId);
            chain.doFilter(req, resp);
            return;
        }

        //不是以上的请求路径就判断是否登录
        Object userId = req.getSession().getAttribute("user");
        //员工id不为空  说明已经登录 放行
        if (userId!=null){
            //放行之前将用户id存进 线程中
            BaseContext.setCurrentId((Long) userId);
            chain.doFilter(req, resp);
            return;
        }


        resp.getWriter().print(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}